from dash import Input, Output, State, callback_context, no_update, html
from models import db, RepairRecord,Product
from datetime import datetime
import dash,time
from server import server
from modules.generatelogs.generatelogs import write_repair_log

def register_repair_complete_callbacks(dash_app):
    # 打开维修完成Modal
    @dash_app.callback(
        Output("repair-complete-modal", "is_open"),
        Output("repair-complete-info", "children"),
        Output("repair-complete-alert", "is_open"),
        Output("repair-complete-alert", "children"),
        Input("repair-complete-button", "n_clicks"),
        State("repair-records-table", "data"),
        State("repair-details-record-id-store", "data"),
        prevent_initial_call=True
    )
    def open_repair_complete_modal(n_clicks, table_data, record_id):
        if not n_clicks or not record_id:
            return no_update, no_update, no_update, no_update
        # 查找该条记录
        record = next((r for r in table_data if r["id"] == record_id), None)
        if not record:
            return no_update, "未找到维修记录", True, "未找到维修记录"
       
        info = html.Div([
            html.Div(f"维修单号: {record['id']}"),
            html.Div(f"设备名称: {record.get('product_name', '')}"),
            html.Div(f"设备编号: {record.get('product_code', '')}"),
            html.Div(f"机构: {record.get('org_shortname', 'hpq')}"),
            html.Div(f"科室: {record.get('department_name', '')}"),
            html.Div(f"故障描述: {record.get('fault_description', '')}"),
            html.Div(f"报修时间: {record.get('report_date', '')}"),
            html.Div(f"报修人: {record.get('repair_caller', '')}"),
        ], style={"marginTop": "20px"})
        return True, info, False, ""

    # 关闭Modal
    @dash_app.callback(
        Output("repair-complete-modal", "is_open", allow_duplicate=True),
        Input("repair-complete-cancel", "n_clicks"),
        State("repair-complete-modal", "is_open"),
        prevent_initial_call=True
    )
    def close_repair_complete_modal(n_cancel, is_open):
        if n_cancel:
            return False
        return no_update

    # 提交维修完成
    @dash_app.callback(
        Output('repair-refresh-flag-complete', 'data'),
        Output("repair-complete-modal", "is_open", allow_duplicate=True),
        Output("repair-complete-alert", "is_open", allow_duplicate=True),
        Output("repair-complete-alert", "children", allow_duplicate=True),
        Input("repair-complete-confirm", "n_clicks"),
        State("repair-complete-info", "children"),
        State("repair-complete-content", "value"),
        State("repair-complete-result", "value"),
        State("repair-type", "value"),  # 新增：维修类型输入
        State("repair-complete-cost", "value"),
        State("repair-complete-parts", "value"),
        State("repair-complete-remarks", "value"),
        prevent_initial_call=True
    )
    def submit_repair_complete(n_submit, info_children, content, result, repair_type, cost, parts, remarks):  # 更新函数参数
        # print("submit_repair_complete called")
        # print("content:", content)
        # print("result:", result)
        # print("repair_type:", repair_type)  # 新增：打印维修类型
        # print("cost:", cost)
        # print("parts:", parts)
        # print("remarks:", remarks)
        # print("n_submit:", n_submit)
        if not n_submit:
            return no_update, no_update, no_update, no_update  # 更新返回值数量
        # 解析维修单号
        record_id = None
        # print("info_children:", info_children)
        try:
            # 先取出 children 列表
            children = info_children.get("props", {}).get("children", []) if isinstance(info_children, dict) else info_children
            for child in children:
                print("child:", child)
                if isinstance(child, dict):
                    text = child.get("props", {}).get("children", "")
                elif isinstance(child, str):
                    text = child
                else:
                    continue
                print("text:", text)
                if "维修单号" in text:
                    record_id = int(text.split(":")[1].strip())
                    break
            print("record_id:", record_id)
            if not record_id:
                return no_update, True, True, "无法获取维修单号"
        except Exception as e:
            return no_update, True, True, f"解析维修单号异常: {e}"
        # 更新数据库
        record = db.session.query(RepairRecord).filter_by(id=record_id).first()
        
        if not record:
            return no_update, True, True, "未找到维修记录"

        # 正确获取设备ID
        product = db.session.query(Product).filter_by(id=record.product_id).first()
        if product:
            product.running_status = 0
            db.session.commit()    
        # 假设你的 RepairRecord 有这些字段，请根据实际表结构调整
        record.repair_content = content
        record.repair_result = result
        record.repair_type = repair_type  # 新增：保存维修类型
        record.repair_cost = cost
        record.parts_replaced = parts
        record.remarks = remarks
        record.repair_status  = "已完成"
        record.actual_completion_date = datetime.now()
        # 计算维修时长（单位：小时，保留两位小数）
        try:
            report_time = record.report_date  # 假设report_date为datetime类型
            complete_time = record.actual_completion_date
            duration = (complete_time - report_time).total_seconds() / 3600
            record.repair_duration = round(duration, 2)
            
        except Exception as e:
            print("维修时长计算异常：", e)
            record.repair_duration = None
        db.session.commit()
        from flask import session
        from models import User
        user_id = session.get("user_id")
        if user_id:
            user = User.query.get(user_id)
            username = user.username if user else "匿名用户"
        else:
            username = "匿名用户"
        from modules.generatelogs.generatelogs import write_repair_log    
        write_repair_log(
            action="完成维修",
            username=username,
            device_id=product.id,
            record_id=record_id,
            message=f"完成人：{username}，描述: 维修内容：{content},维修结果：{result},维修类型：{repair_type},维修费用：{cost},使用备件：{parts},备注：{remarks},维修用时：{round(duration, 2)},"
            )
        return {"refresh": True, "ts": time.time()}, False, False, "维修完成信息已提交"
        



    #处理扫二维码提交维修单
    @dash_app.callback(
        Output('call-repaire-dialog', 'displayed'),
        Output('call-repaire-dialog', 'message'),
        # Output("new-repair-alert2", "children"),
        # Output("new-repair-alert2", "is_open"),
        Output("new-repair-fault2", "value"),
        Output("new-repair-caller2", "value"),
        Input("new-repair-confirm2", "n_clicks"),
        Input("new-repair-cancel2", "n_clicks"),
        State("new-repair-fault2", "value"),
        State("new-repair-caller2", "value"),
        State("url", "pathname"),
        prevent_initial_call=True
    )
    def handle_repair_submit2(submit_clicks, cancel_clicks, fault, caller, pathname):
        # print(f"p171 handle_repair_submit2 called. {fault},{caller},{pathname}")
        ctx = callback_context
        # print(f"p172 handle_repair_submit2 ctx: {ctx}")
        if not ctx.triggered:
            raise dash.exceptions.PreventUpdate

        btn_id = ctx.triggered[0]["prop_id"].split(".")[0]
        # print(f"p174 handle_repair_submit2 btn_id: {btn_id}")

        # 放弃按钮：清空表单并关闭提示
        if btn_id == "new-repair-cancel2":
            return "", False, "", ""

        # 提交按钮
        if btn_id == "new-repair-confirm2":
            
            # 从URL获取设备ID
            try:
                id = int(pathname.split("/")[-1])
                # print(f"p185 handle_repair_submit2 id: {id}")
                product = Product.query.get(id)
                # print(f"p188 handle_repair_submit2 product: {product}")
                if not product:
                    return "设备不存在", True, fault, caller
            except Exception:
                return "设备ID无效", True, fault, caller

            if not fault or not caller:
                return "请填写完整信息", True, fault, caller

            try:
                record = RepairRecord(
                    product_id=product.id,
                    product_name=product.product_name,
                    product_code=product.product_code,
                    org_name=product.org_name,
                    org_shortname_c=product.org_short_name_c,
                    department_name=product.department_name,
                    report_date=datetime.now(),
                    repair_caller=caller,
                    fault_description=fault,
                    is_active=True,
                    create_time=datetime.now(),
                    update_time=datetime.now(),
                    repair_status="待响应"
                )
                # print(f"p205 handle_repair_submit2 record字段：")
                # for c in record.__table__.columns:
                    # print(f"p223 {c.name}: {getattr(record, c.name)}")
                product = db.session.query(Product).filter_by(id=record.product_id).first()
                if product:
                    product.running_status = 1    
                db.session.add(record)
                db.session.commit()
                # print(f"p207 提交成功 handle_repair_submit2 record: {record}")
                from flask import session
                from models import User
                user_id = session.get("user_id")
                if user_id:
                    user = User.query.get(user_id)
                    username = user.username if user else "匿名用户"
                else:
                    username = "匿名用户"
                write_repair_log(
                    action="扫码新建维修",
                    username=username,
                    device_id=product.id,
                    record_id=record.id,
                    message=f"报修人：{caller}，故障描述: {fault}"
                )
                return  True,"提交成功",  "", ""
            except Exception as e:
                db.session.rollback()
                print(f"p208 提交失败 handle_repair_submit2 e: {e}")
                return True,"提交失败", "", ""

        raise dash.exceptions.PreventUpdate